<?php

namespace App\Http\Controllers;

// 用户模型
use App\Models\Business\Business as BusinessModel;//引入用户模型
use App\Models\Product\Product as ProductModel;//引入商品模型
use App\Models\Product\Type as TypeModel;//引入商品类型模型
use App\Models\Product\Cart as CartModel;//引入购物车模型

// 引入Validator 门面 
use Illuminate\Support\Facades\Validator;//引入Validator 门面
use Illuminate\Http\Request;//引入Request类
use Illuminate\Support\Facades\DB;//引入DB类



class Product extends Controller
{
    // 首页
    public function index()
    {
        $recommendlist = ProductModel::where(['status' => '1', 'flag' => '3'])->limit(5)->orderBy('createtime', 'desc')->get();

        $newlist = ProductModel::where(['status' => '1', 'flag' => '1'])->orderBy('createtime', 'desc')->limit(8)->get();

        $hostlist = ProductModel::where(['status' => '1', 'flag' => '2'])->orderBy('createtime', 'desc')->limit(8)->get();

        $data = [
            'recommendlist' => $recommendlist,
            'newlist' => $newlist,
            'hostlist' => $hostlist,
        ];

        return success('', $data);
    }

    // 分类
    public function type()
    {
        $data = TypeModel::orderBy('weigh', 'desc')->get();

        return success('', $data);
    }

    // 列表
    public function list()
    {
        $typeid = request('typeid', 0);
        $keywords = request('keywords', '');
        $flag = request('flag', '');
        $order = request('order', 'createtime');

        $where = [];

        $where['status'] = '1';

        // 分类
        if ($typeid > 0) {
            $where['typeid'] = $typeid;
        }

        if (!empty($flag)) {
            $where['flag'] = $flag;
        }

        // 关键字
        if (!empty($keywords)) {
            $where[] = ['name', 'like', "%$keywords%"];
        }


        $data = ProductModel::where($where)->orderBy($order, 'desc')->get();

        return success('', $data);
    }

    // 详情
    public function info()
    {
        $proid = request('proid', 0);//商品id
        $busid = request('busid', 0);//用户id

        $data = ProductModel::find($proid);//查询商品详情

        $count = CartModel::Where('busid', $busid)->count();//查询购物车数量

        $data['count'] = empty($count) ? '' : $count;//购物车数量 没有为空 否则有值

        return success('', $data);//返回数据
    }

    //客服
    public function mind()
    {
        $url = "http://api.qingyunke.com/api.php";
        $msg = request('msg', '');
        $data = [
            'key' => 'free',
            'msg' => $msg,
        ];
        $paramsStr = http_build_query($data);
        $content = httpRequest($url, $paramsStr, 0);
        $result = json_decode($content, true);
        if ($result) {
            $result['content'] = str_ireplace('{br}', '<br/>', $result['content']);
            return $result;
            exit;
        } else {
            return ['code' => 0, 'content' => '暂时无关键字查询'];
            exit;
        }
    }
}
